package com.itheima.service.impl;

import com.itheima.aspect.Aop;
import com.itheima.mapper.DeptLogMapper;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.pojo.DeptLog;
import com.itheima.service.DeptLogService;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    //注入Mapper对象
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogMapper deptLogMapper;



    @Override
    public List<Dept> list() {
        return deptMapper.list();
    }

    @Aop
    @Override
    @Transactional(rollbackFor = Exception.class) //开启事务管理（方法运行之前开启事务，方法结束之后提交事务，方法运行出异常回滚事务）
    public void deleteById(Integer id) {


        try {
            //1. 根据id删除部门
            deptMapper.deleteById(id);

            //2. 删除该部门下的所有员工
            empMapper.deleteByDeptId(id);
        } finally {
            DeptLog dl = new DeptLog();
            dl.setCreateTime(LocalDateTime.now());
            dl.setDescription("删除了"+id+"部门");
            deptLogMapper.insert(dl);
        }



    }

    @Override
    public void add(Dept dept) {
        //补全基础属性（时间）
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.add(dept);
    }

    @Override
    public Dept getById(Integer id) {
        return deptMapper.getById(id);
    }

    @Override
    public void update(Dept dept) {
        deptMapper.update(dept);
    }
}
